package mycompany.model.chat;

import java.util.ArrayList;
import java.util.List;
import mycompany.helper.HashHelper;
import mycompany.model.UserBaseModel;
import mycompany.model.message.PrivateMessageModel;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
public class PrivateChatModel <U extends UserBaseModel, M extends PrivateMessageModel> extends AbstractChatModel {
    
    public static final int MAX_NUMBER_OF_USERS = 2;
    public static final int MAX_NUMBER_OF_MESSAGES = 30;
    private String passwordHash;
    
    /**
     * Constructs an instance
     * @param id defines chat id
     * @param ownerId defines user id which creates that chat
     */
    public PrivateChatModel(U owner){
        super(owner, MAX_NUMBER_OF_MESSAGES, MAX_NUMBER_OF_USERS);
        passwordHash = HashHelper.sha1("", owner.getName());
    }
    
//    @Override
//    public boolean addUser(UserBaseModel user) {
//        boolean result = super.addUser(user);;
//        if(result) messages.clear(); //claer all messages for new conversation
//        return result;
//    }

    public String getPartnerName(U me){
        for(Object entry : users){
            U user = (U)entry;
            if(!user.equals(me)) return user.getName();
        }
        return null;
    }
    
    public boolean removeMessage(U user, long id){
        M message = (M) getMessageById(id);
        if(message!=null){
            return message.markAsRemoved(user);
        }
        return false;
    }
    
    public List<Long> getRemovedMessagesIds(){
        List<Long> removedMessages = new ArrayList<Long>();
        for(Object entry : messages){
            M message = (M) entry;
            if(message.isRemoved()) removedMessages.add(message.getId());
        }
        return removedMessages;
    }

    @Override
    public void addMessage(UserBaseModel user, String text) {
        PrivateMessageModel message = new PrivateMessageModel(getNextMessageId(), text, user);
        addMessageToList(message, user);
    }
    
    public boolean setPassword(U user, String oldPassword, String newPassword){
        //TODO: user is owner and user can set password(global rule)
        log.info("oldPassword = "+oldPassword);
        log.info("newPassword = "+newPassword);
        if(isValidPassword(oldPassword)){
            passwordHash = HashHelper.sha1(newPassword, user.getName());
            log.info("new: "+passwordHash);
            return true;
        }
        return false;
    }
    
    public boolean isValidPassword(String password){
        //TODO: user is owner and user can set password(global rule)
        String passwordHash = HashHelper.sha1(password, owner.getName());
        log.info("new: "+passwordHash+" - old: "+this.passwordHash);
        return this.passwordHash.equals(passwordHash);
    }
}
